﻿using System;

using System.Collections.Generic;
using System.Text;
using Silvermoon.Shapes;
using System.Drawing;
using Silvermoon.Core;
using Silvermoon.Images;
using Silvermoon.Controls.Base;

namespace Silvermoon.Controls
{
    /// <summary>
    /// An animated control that permanently rotates.
    /// </summary>
    public class AnimatedControl : ChromeControl
    {

        private RotateTransform rotate;
        private int t0;

        public AnimatedControl()
            : base()
        {
            StartDelay = 1000;
            Velocity = 1f;
            Modulo = 45;
            rotate = new RotateTransform { Angle = 0, Axis = RotateAxis.ZAxis };

            Transformation += rotate;
            this.Size = Control.ScaledSize(64, 64);
            OnEnabledChanged();
        }

        protected override Shape CreateDefaultBackground()
        {
            return new BackgroundShape { Texture = SysImages.Busy, Visible = false, Color = Color.Silver, Style = RenderStyle.Simple };
        }
        protected override void Dispose(bool dispose)
        {
            Screen screen = Screen.Current;
            if (screen != null) screen.Tick -= OnTick;
            base.Dispose(dispose);
        }

        public float Velocity { get; set; }

        public int Modulo { get; set; }

        public bool Negative { get; set; }

        protected float Angle
        {
            get { return rotate.Angle; }
            set
            {
                if (rotate.Angle != value)
                {
                    rotate.Angle = value;
                    Invalidate(InvalidationFlag.Appearance);
                }
            }
        }

        public int StartDelay { get; set; }

        protected override void OnEnabledChanged()
        {
            if (Enabled)
            {
                t0 = Environment.TickCount;
                Screen.Current.Tick += new EventHandler<TimeEventArgs>(OnTick);
            }
            else
            {
                Screen.Current.Tick -= OnTick;
                Shape background = Background;
                if (background!=null) background.Visible = false;
            }
            base.OnEnabledChanged();
        }

        void OnTick(object sender, TimeEventArgs e)
        {
            Shape background = Background;
            if ((e.Tick - t0) > StartDelay && background != null) background.Visible = true;
            double v = e.Tick / 2d * Velocity;
            int angle = (int)v;
            angle = (angle % 360);
            if (Modulo > 1) angle = (angle / Modulo) * Modulo;
            if (Negative) angle = -angle;
            Angle = (float)angle;
        }

    }
}
